package com.bci.pwtz.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.JsonUtils;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.service.BusinessCommonService;
import com.bci.pwtz.service.ConfigService;
import com.bci.pwtz.service.cad.Cad_Oper;
import com.bci.pwtz.service.cad.ExecuteCADScr;
import com.bci.pwtz.service.cad.d.DyOper;
import com.bci.pwtz.service.cad.z.Oper;

@Controller
//@Scope("prototype")
public class ExportCADController extends AbstractController{
	@Autowired
	private Cad_Oper cad_Oper;
	@Autowired
	private BusinessCommonService businessCommonService;
	@Autowired
	private Oper oper;
	@Autowired
	private DyOper dyOper;
	@Autowired
	private ConfigService config;
	
	@RequestMapping(value="/user/exportcad")
	@ResponseBody
	public Map exportcad(HttpServletRequest req,String deviceID,Long deviceType){
		try {
			String deviceName = businessCommonService.getDeviceName(deviceType, deviceID);
			String path = "";
            if(PwtzConstants.THE_SERVER_TYPE==1){
                path=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
            }else{
                path=request.getSession().getServletContext().getRealPath("/")+"/upload/";
                path = path.replaceAll("\\\\", "/");    //本地
            }
//          path = path.replaceAll("/", "\\\\");    //服务器
			CompanyUser companyUser = (CompanyUser)session.getAttribute("user");
//			String ret = cad_Oper.drawTpt(path,companyUser.getLastCompanyId(), deviceID, deviceName);
			String ret = dyOper.draw(path,companyUser.getLastCompanyId(), deviceID, deviceType);
			if(ret != null){
			    if(PwtzConstants.THE_SERVER_TYPE==1){
			        return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,ret);
			    }else{
			        return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,ret);
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_INFO,null,"导出失败,请确保设备为有效的经纬度");
	}
	
	@RequestMapping(value="/user/z/exportcad")
	@ResponseBody
	public Map exportzcad(HttpServletRequest req,String deviceID){
		try {
		    String path = "";
            if(PwtzConstants.THE_SERVER_TYPE==1){
                path=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
            }else{
                path=request.getSession().getServletContext().getRealPath("/")+"/upload/";
                path = path.replaceAll("\\\\", "/");    //本地
            }
//          path = path.replaceAll("/", "\\\\");    //服务器
			CompanyUser companyUser = (CompanyUser)session.getAttribute("user");
			String ret = oper.draw(path, companyUser.getLastCompanyId(), deviceID);
			if(ret != null){
				return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,ret);
			}
		} catch (Exception e) {
			e.printStackTrace();
			_log.error(e.getMessage(), e);
		}
		return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_INFO,null,"导出失败,请确保设备为有效的经纬度");
	}
	
	@RequestMapping("/download/{fileName}.scr")
	public void dowload(HttpServletRequest request,HttpServletResponse response,@PathVariable String fileName){
		try {
			String filePath = "";
			if(PwtzConstants.THE_SERVER_TYPE==1){
			    filePath = PwtzConstants.WEB_REAL_PATH+"\\upload\\"+fileName+".scr";
			}else{
			    filePath = PwtzConstants.WEB_REAL_PATH+"/upload/"+fileName+".scr";
			}
			File file = new File(filePath);
			if(file.exists()){
				OutputStream out = response.getOutputStream();
				InputStream in = new FileInputStream(file);
				
				response.setHeader("Content-type", "application/octet-stream");
				response.setHeader("Accept-Length", String.valueOf(in.available()));
				
				int len = 0;
				byte[] by = new byte[1024];
				while( (len = in.read(by)) != -1 ){
					out.write(by, 0, len);
				}
			}
			
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		}
	}
	
	@RequestMapping("/view/{fileName}.scr")
	public String view(HttpServletRequest request,HttpServletResponse response,@PathVariable String fileName){
		try {
		    String filePath = "";
            if(PwtzConstants.THE_SERVER_TYPE==1){
                filePath = PwtzConstants.WEB_REAL_PATH+"\\upload\\"+fileName+".scr";
            }else{
                filePath = PwtzConstants.WEB_REAL_PATH+"/upload/"+fileName+".scr";
            }
			File file = new File(filePath);
			if(file.exists()){
				_log.debug("开始生成dwg文件。。。");
//				String outFilePath = ExecuteCADScr.execute(fileName);//本地执行scr
				String outFilePath = executeSCR(filePath);//外部执行scr
				_log.debug("生成dwg文件结束：文件路径"+outFilePath);
				if(outFilePath == null){
					return "user/m/showCAD";
				}
				
				String showCADMethd = config.getConfigByKey("showCADMethd");
				request.setAttribute("showCADMethd", showCADMethd);
				//通过外部网页浏览cad
				if("0".equals(showCADMethd)){
					String uploadUrl = config.getConfigByKey("cadUploadOutsideUrl");
					_log.debug("cadUploadOutsideUrl="+uploadUrl);
					
					Map fileMap = new HashMap<String, String>();
					fileMap.put(config.getConfigByKey("cadUploadOutsideKey"), outFilePath);
					InputStream in = ExecuteCADScr.formUpload(uploadUrl, null, fileMap);
					String info = ExecuteCADScr.getMessage(in);
					
					Map map = JsonUtils.json2bean(info, Map.class);
					double reurnCode = (Double) map.get("error");
					//成功
					if(reurnCode == 0){
						String cadUrl = config.getConfigByKey("cadBrowseOutsideUrl")+map.get("url");
						request.setAttribute("cadUrl", cadUrl);
					}
				}else{
					request.setAttribute("cadUrl","upload/"+fileName+".dwg");
				}
			}
			
		} catch (Exception e) {
			_log.error(e.getMessage(), e);
		}
		return "user/m/showCAD";
	}
	
	private String executeSCR(String filePath) throws PwtzDatabaseException{
		String fileName = ExecuteCADScr.getFileName(filePath);
		String outFilePath = "";
        if(PwtzConstants.THE_SERVER_TYPE==1){
            outFilePath = PwtzConstants.WEB_REAL_PATH+"\\upload\\"+fileName+".dwg";
        }else{
            outFilePath = PwtzConstants.WEB_REAL_PATH+"/upload/"+fileName+".dwg";
        }
		
		String uploadUrl = config.getConfigByKey("cadSCRExecuteURL");
		_log.debug("cadSCRExecuteURL="+uploadUrl);
		
		Map fileMap = new HashMap<String, String>();
		fileMap.put("filename", filePath);
		
		InputStream in = ExecuteCADScr.formUpload(uploadUrl, null, fileMap);
		
		outFilePath = ExecuteCADScr.writeFile(in,outFilePath);
		return outFilePath;
	}
}
